package com.ggh.jinjilive.ui.social.message;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.FragmentMessageBinding;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.pagestatus.EmptyCallback;
import com.ggh.jinjilive.pagestatus.LoadingCallback;
import com.ggh.jinjilive.ui.BaseFragment;
import com.ggh.jinjilive.ui.social.message.adapter.MessageAdapter;
import com.ggh.jinjilive.ui.social.message.chat.ChatPageActivity;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMConversationListener;
import com.tencent.imsdk.v2.V2TIMConversationResult;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class MessageFragment extends BaseFragment<FragmentMessageBinding> implements OnRefreshListener, OnLoadMoreListener {
    private long nextSeq = 0;
    //消息适配器
    private MessageAdapter messageAdapter;
    //消息未读变换
    private AddItemOnClickListener addItemOnClickListener;
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return R.layout.fragment_message;
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        View contentView = binding.getRoot().findViewById(R.id.refreshLayout);
        loadService = LoadSir.getDefault().register(contentView, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                onRefresh(binding.refreshLayout);
            }
        });
        loadService.showCallback(LoadingCallback.class);
        onRefresh(binding.refreshLayout);
    }

    @Override
    public void initView() {
        super.initView();
        binding.refreshLayout.setRefreshHeader(new MaterialHeader(mContext));
        binding.refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        //消息适配器
        messageAdapter = new MessageAdapter(mContext);
        messageAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                V2TIMMessage v2TIMMessage = (V2TIMMessage) mObject;
                if(null != v2TIMMessage){
                    Intent intent =new Intent(mContext, ChatPageActivity.class);
                    intent.putExtra("v2TIMMessage",v2TIMMessage);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);//启动Activity
                }
            }
        });
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        binding.recyclerView.setAdapter(messageAdapter);
    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //刷新
        binding.refreshLayout.setOnRefreshListener(this);
        //加载
        binding.refreshLayout.setOnLoadMoreListener(this);
        //设置会话监听器
        V2TIMManager.getConversationManager().setConversationListener(new V2TIMConversationListener() {
            @Override
            public void onSyncServerStart() {
                super.onSyncServerStart();
                //同步服务器会话开始，SDK 会在登录成功或者断网重连后自动同步服务器会话，您可以监听这个事件做一些 UI 进度展示操作。
                LogUtils.d("同步服务器会话开始，SDK 会在登录成功或者断网重连后自动同步服务器会话，您可以监听这个事件做一些 UI 进度展示操作。");
                onRefresh(binding.refreshLayout);
            }

            @Override
            public void onSyncServerFinish() {
                super.onSyncServerFinish();
                LogUtils.d("同步服务器会话完成，如果会话有变更，会通过 onNewConversation | onConversationChanged 回调告知客户");
                onRefresh(binding.refreshLayout);
            }

            @Override
            public void onNewConversation(List<V2TIMConversation> conversationList) {
                super.onNewConversation(conversationList);
                LogUtils.d("有新的会话（比如收到一个新同事发来的单聊消息、或者被拉入了一个新的群组中），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序");
                if(null != messageAdapter){
                    messageAdapter.setADD(conversationList);
                }
            }

            @Override
            public void onConversationChanged(List<V2TIMConversation> conversationList) {
                super.onConversationChanged(conversationList);
                LogUtils.d("某些会话的关键信息发生变化（未读计数发生变化、最后一条消息被更新等等），可以根据会话的 lastMessage -> timestamp 重新对会话列表做排序" + conversationList.size());
                onRefresh(binding.refreshLayout);
            }

            @Override
            public void onTotalUnreadMessageCountChanged(long totalUnreadCount) {
                super.onTotalUnreadMessageCountChanged(totalUnreadCount);
                LogUtils.d("会话未读总数变更通知" + totalUnreadCount);
                if(null != addItemOnClickListener){
                    addItemOnClickListener.onSkipClicked((int)totalUnreadCount,null);
                }
            }
        });
    }

    /**
     * 未读
     * @param addItemOnClickListener
     */
    public void setAddItemOnClickListener(AddItemOnClickListener addItemOnClickListener){
        this.addItemOnClickListener = addItemOnClickListener;
    }




    @Override
    public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
        nextSeq = 0;
        getConversationList();
    }

    @Override
    public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
        nextSeq = nextSeq + 1;
        getConversationList();
    }

    /**
     * 	获取会话列表
     */
    private void getConversationList(){
        V2TIMManager.getConversationManager().getConversationList(nextSeq, 100, new V2TIMValueCallback<V2TIMConversationResult>() {
            @Override
            public void onSuccess(V2TIMConversationResult v2TIMConversationResult) {
                binding.refreshLayout.finishRefresh();
                if (nextSeq == 0) {
                    if (v2TIMConversationResult.getConversationList().size() > 0) {
                        messageAdapter.ADD(v2TIMConversationResult.getConversationList());
                        binding.refreshLayout.finishLoadMore();//结束刷新
                        loadService.showSuccess();
                    } else {
                        loadService.showCallback(EmptyCallback.class);
                    }
                }else {
                    if(null != v2TIMConversationResult.getConversationList() && v2TIMConversationResult.getConversationList().size() > 0){
                        messageAdapter.setAdd(v2TIMConversationResult.getConversationList());
                        binding.refreshLayout.finishLoadMore();//结束刷新
                    }else {
                        binding.refreshLayout.finishLoadMoreWithNoMoreData();//结束刷新
                    }
                }

            }

            @Override
            public void onError(int code, String desc) {
                ToastUtils.make().show(code + "获取会话列表失败" + desc);
            }
        });
    }


}
